<?php
require_once __DIR__ . '/../vendor/autoload.php';

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Exchange\AMQPExchangeType;

$config = [
    'host' => '127.0.0.1',
    'vhost' => '/',
    'port' => 5672,
    'login' => 'guest',
    'password' => 'guest',
];

$exchange = 'pubSub'; // 交换器名称

try {
    //建立连接到RabbitMQ服务器
    $connection = new AMQPStreamConnection($config['host'], $config['port'], $config['login'], $config['password'], $config['vhost']);
    //建立通道
    $channel = $connection->channel();
    //声明一个交换机,交换器类型定义fanout。
    $channel->exchange_declare($exchange, AMQPExchangeType::FANOUT, false, false, false);

    // 生产10条消息
    for ($i = 0; $i < 10; $i++) {
        $body = "发布/订阅模式下生成第【" . ($i + 1) . "】条消息";
        $message = new AMQPMessage($body, ['content_type' => 'text/plain', 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT]);
        $channel->basic_publish($message, $exchange);
        echo ' [x] Send ' . $body . "\n";
        sleep(1);
    }
    $channel->close(); // 关闭通道
    $connection->close(); // 关闭连接
} catch (Exception $e) {
    die($e->getMessage());
}